<template>
  <div class="museum-creative">
    <!-- 导航栏 -->
    <div class="nav-container">
      <div class="logo">
        <span class="logo-text">文创</span>
      </div>
      <ul class="nav-menu">
        <li class="nav-item">
          <router-link to="/museum" class="nav-link">首页</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/allproducts" class="nav-link">全部商品</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/consultation" class="nav-link">文化资讯</router-link>
        </li>
        <li class="nav-item">
          <router-link v-if="!isLoggedIn()" to="/login" class="nav-link">登录</router-link>
          <router-link v-if="isLoggedIn()" to="/museum" class="nav-link" @click.prevent="logout">退出</router-link>
        </li>
        <li class="nav-item">
          <a class="nav-link cart-icon" @click.prevent="openShoppingCart">
            <img src="@/assets/img/btn_waiter_sel.png" alt="购物车" class="cart-img">
            <span v-if="cartItemCount > 0" class="cart-badge">{{ cartItemCount }}</span>
          </a>
        </li>
      </ul>
    </div>

    

    <!-- 筛选和搜索区域 -->
    <div class="filter-section fade-in">
      <div class="search-box">
        <input type="text" v-model="searchQuery" placeholder="搜索商品..." @input="filterProducts">
        <button class="search-btn"><i class="search-icon">🔍</i></button>
      </div>
      <div class="sort-options">
        <span>排序方式：</span>
        <button :class="['sort-btn', sortBy === 'default' ? 'active' : '']" @click="setSortBy('default')">默认</button>
        <button :class="['sort-btn', sortBy === 'priceAsc' ? 'active' : '']" @click="setSortBy('priceAsc')">价格 ↑</button>
        <button :class="['sort-btn', sortBy === 'priceDesc' ? 'active' : '']" @click="setSortBy('priceDesc')">价格 ↓</button>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="products-section fade-in">
      <div class="products-grid" v-if="displayedProducts.length > 0">
        <div v-for="(product, index) in displayedProducts" :key="index" class="product-card" @click="viewProductDetail(product)">
          <div class="product-image-container">
            <img :src="getImageUrl(product.image)" :alt="product.name" class="product-image">
          </div>
          <div class="product-details">
            <h3 class="product-name">{{ product.name }}</h3>
            <div class="product-price">¥ {{ product.price.toFixed(2) }}</div>
            <button class="add-to-cart" @click.stop="addToCart(product)">
              <span class="icon">+</span>
              加入购物车
            </button>
          </div>
        </div>
      </div>
      <div v-else class="no-products">
        <div class="empty-state">
          <div class="empty-icon">🔍</div>
          <h3>未找到商品</h3>
          <p>尝试使用其他关键词搜索</p>
        </div>
      </div>
    </div>

    <!-- 商品详情(默认隐藏) -->
    <div v-if="showProductDetail" class="product-detail fade-in">
      <div class="product-gallery">
        <img :src="getImageUrl(selectedProduct.image)" :alt="selectedProduct.name" class="main-image">
        <div class="thumbnail-container">
          <img v-for="(img, index) in selectedProduct.images" :key="index" :src="img"
            :alt="selectedProduct.name + ' 图片 ' + (index + 1)" class="thumbnail"
            :class="{ active: index === selectedImageIndex }" @click="selectedImageIndex = index">
        </div>
      </div>
      <div class="product-info">
        <h1 class="product-title">{{ selectedProduct.name }}</h1>
        <div class="price-container">
          <span class="current-price">¥ {{ selectedProduct.price.toFixed(2) }}</span>
          <span v-if="selectedProduct.originalPrice" class="original-price">
            ¥ {{ selectedProduct.originalPrice.toFixed(2) }}
          </span>
          <span v-if="selectedProduct.discount" class="discount-tag">
            {{ selectedProduct.discount }}折
          </span>
        </div>
        <p class="product-description">{{ selectedProduct.description }}</p>

        <div class="quantity-selector">
          <span class="quantity-label">数量</span>
          <div class="quantity-controls">
            <button class="quantity-btn" @click="decreaseQuantity">-</button>
            <input type="number" v-model="quantity" min="1" class="quantity-input">
            <button class="quantity-btn" @click="increaseQuantity">+</button>
          </div>
        </div>

        <div class="action-buttons">
          <button class="buy-now" @click="buyNow(selectedProduct)">立即购买</button>
          <button class="add-to-cart-detail" @click="addToCart(selectedProduct)">加入购物车</button>
        </div>
        <div class="appraise-wrapper">
          <button class="appraise" @click="appraise(selectedProduct)">评价商品</button>
        </div>
      </div>
    </div>

    <!-- 用户评价部分 -->
    <div v-if="showProductDetail" class="reviews-section fade-in" @click="appraiselist(selectedProduct)">
      <h2 class="section-title">用户评价</h2>
      <div class="review-card" v-for="(review, index) in reviews" :key="index">
        <div class="reviewer-info">
          <span class="reviewer-name">{{ review.username }}</span>
          <span class="review-date">{{ review.date }}</span>
        </div>
        <div class="rating">
          <span v-for="i in review.rating" :key="i">★</span>
          <span v-for="i in 5 - review.rating" :key="'empty-' + i" class="empty-star">☆</span>
        </div>
        <p class="review-text">{{ review.content }}</p>
      </div>
    </div>

    <!-- 评价表单 -->
    <div v-if="showReviewForm">
      <form @submit.prevent="submitForm" class="review-form">
        <h3>商品评价</h3>
        <button type="button" class="close-btn" @click="closeReviewForm">&times;</button>
        <div>
          <label for="rating" class="rating-label">评分:</label>
          <select v-model="rating" id="rating">
            <option value="1">1星</option>
            <option value="2">2星</option>
            <option value="3">3星</option>
            <option value="4">4星</option>
            <option value="5">5星</option>
          </select>
        </div>
        <div>
          <label for="content">评价内容:</label>
          <textarea v-model="content" id="content" rows="4" placeholder="请分享您对商品的使用体验..." required></textarea>
        </div>
        <div>
          <button type="submit">提交评价</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
// 导入所需的组件和库
import api from '@/assets/js/api.js'; // 导入API接口
import { ref, reactive, onMounted, computed } from 'vue'; // 导入Vue组合式API
import { useRouter } from 'vue-router'; // 导入路由
import { ElMessage } from 'element-plus'; // 导入Element Plus的消息提示

// 获取路由实例
const router = useRouter();

// 商品数据
const allProducts = ref([]); // 存储所有从API获取的商品
const displayedProducts = ref([]); // 当前显示的商品

// 搜索和筛选
const searchQuery = ref('');
const sortBy = ref('default');

// 产品详情相关数据
const showProductDetail = ref(false);
const selectedProduct = ref({});
const selectedImageIndex = ref(0);
const quantity = ref(1);

// 用户评价
const reviews = ref([]);

// 评价表单数据
const rating = ref("5");
const content = ref("");
const showReviewForm = ref(false);

// 购物车数量
const cartItemCount = ref(0);

// 页面加载时获取商品数据
onMounted(() => {
  fetchProducts();
});

// 检查用户是否已登录
function isLoggedIn() {
  // 检查localStorage中是否存在userId
  return localStorage.getItem('userId');
}

// 退出登录
async function logout() {
  const result = await api.out();
  if (result.data == "退出成功") {
    localStorage.clear();
    location.reload();
  }
}

// 提交评价表单
async function submitForm() {
  const reviewData = {
    rating: Number(rating.value),
    content: content.value,
    productId: selectedProduct.value.id, // 关联的商品ID
    userId: Number(localStorage.getItem('userId')), // 用户ID从localStorage获取
  };
  await api.addReview(reviewData);
  showReviewForm.value = false;
  window.location.reload();
}

// 获取商品评论
async function appraiselist(product) {
  const result = await api.getProductReviews(product.id);
  if (result.code === 200 && result.data) {
    reviews.value = result.data.map(item => ({
      username: item.username,
      content: item.content,
      rating: item.rating,
      date: item.date || '刚刚'
    }));
  }
}

// 获取商品数据
async function fetchProducts() {
  try {
    const result = await api.product();
    if (result.code === 200 && result.data) {
      allProducts.value = result.data;
      displayedProducts.value = [...allProducts.value];
    }
  } catch (error) {
    console.error('获取商品数据失败:', error);
  }
}

// 补全图片地址
function getImageUrl(imagePath) {
  return `http://localhost:8080${imagePath}`;
}

// 查看商品详情
function viewProductDetail(product) {
  selectedProduct.value = product;
  selectedImageIndex.value = 0;
  quantity.value = 1;
  showProductDetail.value = true;
  // 滚动到详情部分
  setTimeout(() => {
    const detailElement = document.querySelector('.product-detail');
    if (detailElement) {
      detailElement.scrollIntoView({ behavior: 'smooth' });
    }
  }, 100);
  appraiselist(selectedProduct.value);
}

// 数量控制
function increaseQuantity() {
  quantity.value++;
}

function decreaseQuantity() {
  if (quantity.value > 1) {
    quantity.value--;
  }
}

// 添加到购物车
async function addToCart(product) {
  if (!isLoggedIn()) {
    // 用户未登录，提示登录
    ElMessage.warning('请先登录后再添加商品到购物车');
    router.push('/login');
    return;
  }
  
  try {
    const cartItem = {
      userId: Number(localStorage.getItem('userId')),
      productId: product.id,
      productName: product.name,
      productImage: product.image,
      price: product.price,
      quantity: quantity.value,
    }
    await api.addToCart(cartItem);
    
    // 提示添加成功
    ElMessage.success(`${product.name} 已添加到购物车`);
  } catch (error) {
    console.error('添加到购物车失败:', error);
    ElMessage.error('添加到购物车失败');
  }
}

// 立即购买
function buyNow(product) {
  // 添加到购物车
  addToCart(product);
  // 跳转到购物车页面
  router.push('/shoppingcart');
}

// 打开购物车页面
function openShoppingCart() {
  router.push('/shoppingcart');
}

// 评价商品
function appraise(product) {
  selectedProduct.value = product;
  showReviewForm.value = true;
}

// 关闭评价表单
function closeReviewForm() {
  showReviewForm.value = false;
}

// 筛选和排序商品
function filterProducts() {
  let filtered = [...allProducts.value];
  
  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(product => 
      product.name.toLowerCase().includes(query) || 
      (product.description && product.description.toLowerCase().includes(query))
    );
  }
  
  // 排序
  switch (sortBy.value) {
    case 'priceAsc':
      filtered.sort((a, b) => a.price - b.price);
      break;
    case 'priceDesc':
      filtered.sort((a, b) => b.price - a.price);
      break;
    default:
      // 默认排序，保持原顺序
      break;
  }
  
  displayedProducts.value = filtered;
}

// 设置排序方式
function setSortBy(type) {
  sortBy.value = type;
  filterProducts();
}
</script>

<style scoped>
/* 引入基础CSS文件 */
@import '../../assets/css/museum-product.css';

/* 全部商品页面特定样式 */
.page-header {
  text-align: center;
  margin: 20px 0 30px;
  padding: 20px 0;
  background: linear-gradient(to right, rgba(156, 39, 176, 0.1), rgba(103, 58, 183, 0.1));
  border-radius: 8px;
}

.page-header h1 {
  font-size: 32px;
  color: #333;
  font-weight: 600;
  position: relative;
  display: inline-block;
}

.page-header h1:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(to right, #9c27b0, #673ab7);
  border-radius: 3px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 15px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-box {
  display: flex;
  align-items: center;
  width: 300px;
  position: relative;
}

.search-box input {
  width: 100%;
  padding: 10px 40px 10px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.search-box input:focus {
  border-color: #9c27b0;
  box-shadow: 0 0 0 2px rgba(156, 39, 176, 0.2);
  outline: none;
}

.search-btn {
  position: absolute;
  right: 10px;
  background: none;
  border: none;
  cursor: pointer;
  color: #666;
  font-size: 16px;
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sort-options span {
  font-size: 14px;
  color: #666;
}

.sort-btn {
  padding: 6px 12px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.sort-btn:hover {
  background-color: #eee;
}

.sort-btn.active {
  background-color: #9c27b0;
  color: white;
  border-color: #9c27b0;
}

.no-products {
  width: 100%;
  padding: 60px 0;
  text-align: center;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 20px;
  color: #ccc;
}

.empty-state h3 {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.empty-state p {
  color: #666;
  font-size: 14px;
}
</style>